package com.mcxx.common.service.impl;

import cn.hutool.core.util.IdUtil;
import com.mcxx.common.exception.BizException;
import com.mcxx.common.service.ReferenceService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.miniSalvation.order.dto.OrderCertDTO;
import com.mcxx.modules.miniSalvation.order.entity.OrderCertEntity;
import com.mcxx.modules.miniSalvation.order.service.read.OrderCertReadService;
import com.mcxx.modules.miniSalvation.order.service.write.OrderCertWriteService;
import com.mcxx.modules.temporary.order.entity.TmpOrderCertEntity;
import com.mcxx.modules.temporary.order.service.read.TmpOrderCertReadService;
import com.mcxx.modules.temporary.order.service.write.TmpOrderCertWriteService;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;


@Service
@TaTransactional
public class ReferenceServiceImpl extends BaseService implements ReferenceService {

    private static final Logger logger = LoggerFactory.getLogger(ReferenceServiceImpl.class);

    @Autowired
    private FileService fileService;
    @Autowired
    private OrderCertWriteService orderCertWriteService;
    @Autowired
    private OrderCertReadService orderCertReadService;
    @Autowired
    private TmpOrderCertWriteService tmpOrderCertWriteService;
    @Autowired
    private TmpOrderCertReadService tmpOrderCertReadService;
    @Value("${yinhai.fileserver.bucketId:society-test}")
    private String BUCKET_ID;


    @Override
    public Map<String, String> upload(MultipartFile file, OrderCertDTO orderCertDTO) {
        String objectkey = null;
        try {

            logger.info("正在上传证明材料，文件名称：{}", file.getOriginalFilename());
            objectkey = fileService.upload(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            logger.error("证明材料上传失败");
            throw new BizException(FailureCode.ERR_20078);
        }
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String certId = IdUtil.simpleUUID();


        OrderCertEntity orderCertEntity = new OrderCertEntity();
        orderCertEntity.setId(certId);
        orderCertEntity.setImgName(fileName);
        orderCertEntity.setImgPixName(suffix);
        orderCertEntity.setImgUrl(objectkey);
        orderCertEntity.setFileType(orderCertDTO.getFileType());
        orderCertEntity.setAssociationTable(orderCertDTO.getAssociationTable());
        orderCertEntity.setAssociationTableId(orderCertDTO.getAssociationTableId());
        orderCertEntity.setOrderId(orderCertDTO.getOrderId());
        orderCertEntity.setUserLevel(orderCertDTO.getUserLevel());

        if (Constant.BusinessCode.LINSHI.equals(orderCertDTO.getBusinessType())) {
            TmpOrderCertEntity tmpOrderCertEntity = new TmpOrderCertEntity();
            BeanUtils.copyProperties(orderCertEntity, tmpOrderCertEntity);
            tmpOrderCertWriteService.insertIgnoreNull(tmpOrderCertEntity);
        } else{
            orderCertWriteService.insertIgnoreNull(orderCertEntity);
        }


        Map<String, String> map = new HashMap<>();
        map.put("status", "1");
        map.put("certId", certId);
        return map;
    }


    @Override
    public void deleteById(String id,String businessType, int curUserLevel) {

        String fileKey = null;
        if (Constant.BusinessCode.LINSHI.equals(businessType)) {
            TmpOrderCertEntity orderCertEntity = tmpOrderCertReadService.getFileKeyAndUserLevelById(id);
            if (orderCertEntity.getUserLevel() != null && curUserLevel > orderCertEntity.getUserLevel()) {

                throw new BizException("-1","不能删除上级上传的材料");
            }
            fileKey = orderCertEntity.getImgUrl();

            tmpOrderCertWriteService.deleteById(id);
        } else {
            OrderCertDTO orderCertDTO = orderCertReadService.getFileKeyAndUserLevelById(id);
            if (orderCertDTO.getUserLevel() != null && curUserLevel > orderCertDTO.getUserLevel()) {

                throw new BizException("-1","不能删除上级上传的材料");
            }
            fileKey = orderCertDTO.getImgUrl();

            orderCertWriteService.deleteById(id);
        }
        if (fileKey == null) {
            throw new BizException(FailureCode.ERR_10003);
        }


        fileService.deleteByObjectId(fileKey);
    }


    @Override
    public void batchDelete(String[] ids,String businessType) {

        List<String> fileKeys;
        if (Constant.BusinessCode.LINSHI.equals(businessType)) {
            fileKeys = tmpOrderCertReadService.listFileKeyByIds(ids);

            tmpOrderCertWriteService.batchDelete(ids);
        } else {
            fileKeys = orderCertReadService.listFileKeyByIds(ids);

            orderCertWriteService.batchDelete(ids);
        }


        fileService.batchDeleteByObjectId(fileKeys);
    }

    @Override
    public void batchUpdate(String[] ids,String businessType,String nid) {
    }

}
